﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Geek7Utils
{
    class Sercert
    {
        static int[] pi10000 = new int[] {
            3,0,1,3,0,5,2,7,9,3,2,0,5,4,2,7,4,6,2,8,6,5,4,0,3,6,0,3,6,7,4,5,3,2,8,6,5,1,0,5,7,0,6,5,8,7,4,8,8,2,2,5,6,9,8,1,5,7,9,3,6,7,8,9,7,6,6,9,7,4,2,2,0,5,7,5,0,5,9,6,8,3,4,4,0,8,6,9,7,3,5,0,2,0,1,4,1,0,2,0,6,7,2,3,5,8,5,0,2,0,0,7,2,4,5,2,2,5,6,3,2,6,5,1,3,4,1,0,5,5,9,2,4,0,1,9,0,2,7,4,2,1,6,2,4,8,4,3,9,1,4,0,3,5,9,9,8,9,5,3,5,3,9,4,5,9,0,9,4,4,0,7,0,4,6,9,1,2,0,9
        };

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ts"> 时间戳 </param>
        /// <returns></returns>
        public static int GetSercert(int ts)
        {
            ts = ts < 0 ? 0 : ts;

            int[] cells = new int[8];
            int len = cells.Length;
            for (int i = 0; i < len; i++)
            {
                cells[i] = ts % (int)Math.Pow(10, i + 1);
            }
            int arrLen = pi10000.Length;
            int ID = 0;
            for (int i = 0; i < len; i++)
            {
                int index = cells[i] % arrLen;
                ID += pi10000[index] * (int)Math.Pow(10, i);
            }

            return ID;
        }


        /// <summary>
        /// 获取指定时间的 时间戳 毫秒级
        /// </summary>
        /// <param name="milllTimeStamp"> 当前时间 你可以传入 本地时间 或者 UTC </param>
        /// <returns>时间戳 毫秒级</returns>
        public static Int64 GetTimeStamp(DateTime now)
        {
            TimeSpan ts = now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds);
        }

        /// <summary>
        /// 将指定时间戳转换成DateTime对象
        /// </summary>
        /// <param name="milllTimeStamp"> 时间戳 毫秒级 </param>
        /// <returns> DateTime对象 </returns>
        public static DateTime Convert2DateTime(Int64 milllTimeStamp )
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(milllTimeStamp);
        }

        /// <summary>
        /// 验证包
        /// </summary>
        /// <param name="ts"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static bool Verify(string ts, string secret)
        {
            Int64 timestamp = Convert.ToInt64(ts);
            var time = Convert2DateTime(timestamp);

            if (Math.Abs(DateTime.Now.Second - time.Second) < 5)
            {
                return GetSercert((int)timestamp) == Convert.ToInt32(secret);
            }

            return false;
        }
    }
}
